from django.http import HttpResponse
from django.shortcuts import render
from myadmin import models

# Create your views here.

def index(request):
    return render(request, 'myadmin/index.html')

# 后台登入页面，接受get请求
def mylogin(request):
    return render(request, 'myadmin/login.html')

# 后台登入验证，只能接受post请求
def relogin(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken")
    # print(data)

    # 检测验证码，添加不区分大小写
    # request.session['verifycode']记录的是生成的验证码，data['code']是输入的验证码
    if request.session['verifycode'].lower() != data['code'].lower():
        return HttpResponse('<script>alert("验证码错误");history.back();</script>')

    # 检测用户
    # {'phonenum': '17702705873', 'password': '123455', 'code': '8N1A'}
    # print(data)
    # models.bookshop_users.object.get方法，找不到报错；找到多次也报错
    obj = models.bookshop_users.objects.filter(phonenum=data['phonenum'])
    if obj.count() == 0:
        return HttpResponse('<script>alert("用户不存在");history.back();</script>')

    # 验证密码
    if data['password'] == obj[0].password:
        # 登入成功后，需要记录下用户痕迹
        request.session['successuser'] = {'id': obj[0].id, 'phone': obj[0].phonenum }

        return HttpResponse('<script>alert("登入成功");location.href="/myadmin/";</script>')
    else:
        return HttpResponse('<script>alert("密码错误123");history.back();</script>')

    # from django.contrib.auth.hashers import make_password, check_password
    # if check_password(data['password'], obj[0].password):
    #     # 完成登入操作
    #     # 记录用户登入session
    #     request.session['successuser'] = {'id': obj[0].id, 'phone': obj[0].phonenum }
    #     return HttpResponse('<script>alert("登入成功");location.herf="/myadmin/";</script>')
    # else:
    #     return HttpResponse('<script>alert("密码错误123");history.back();</script>')

# 验证码
def verifycode(request):
    # 引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    # 定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象，选择字体，windows在/windows/fronts中
    font = ImageFont.truetype('Kohinoor.ttc', 23)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')